package appCache

import (
	"encoding/gob"
	"fmt"
	"io"
	"os"
	"runtime"
	"sync"
	"time"
)




//Item 缓存项
type Item struct {
	Object      interface{} //缓存对象
	Expiration  int64       //过期时间
	firstNotify bool        //过期前是否通知
	Count       int64       //访问次数
}

//Expired 判断是否到期
func (i *Item) Expired() DataInvalid {
	if i.Expiration == 0 {
		return Normal
	}
	if time.Now().UnixNano() > i.Expiration {
		return Expire
	}
	return Normal
}

//DataInvalid 数据老化情况
type DataInvalid int
const (
	NoExpiration 	  time.Duration = -1   //不过期
	DefaultExpiration time.Duration = 0 //默认到期时间

	Normal     DataInvalid = 0 // 正常(未过期)
	Expire     DataInvalid = 1 // 已到期
	WillExpire DataInvalid = 2 // 即将到期
)

//Cache 缓存
type Cache struct {
	*cache
	// If this is confusing, see the comment at the bottom of New()
}

// cache 缓存
type cache struct {
	defaultExpiration time.Duration
	willExpire        time.Duration
	items             map[string]*Item
	mu                sync.RWMutex
	onEvicted         func(items ...CleanItem)
	janitor           *janitor
}

//Set 设置缓存
func (c *cache) Set(k string, x interface{}, d time.Duration) {
	var e int64
	if d == DefaultExpiration {
		d = c.defaultExpiration
	}
	if d > 0 {
		e = time.Now().Add(d).UnixNano()
	}
	c.mu.Lock()
	c.items[k] = &Item{
		Object:     x,
		Expiration: e,
		firstNotify: false,
		Count:      0,
	}
	c.mu.Unlock()
}

//set 设置缓存[内部使用未加锁]
func (c *cache) set(k string, x interface{}, d time.Duration) {
	var e int64
	if d == DefaultExpiration {
		d = c.defaultExpiration
	}
	if d > 0 {
		e = time.Now().Add(d).UnixNano()
	}
	c.items[k] = &Item{
		Object:      x,
		Expiration:  e,
		firstNotify: false,
		Count:       0,
	}
}

//SetDefault 设置默认到期时间
func (c *cache) SetDefault(k string, x interface{}) {
	c.Set(k, x, DefaultExpiration)
}

//Get 获取缓存
func (c *cache) Get(k string) (interface{}, bool) {
	c.mu.RLock()
	item, found := c.items[k]
	if !found {
		c.mu.RUnlock()
		return nil, false
	}
	if item.Expiration > 0 {
		if time.Now().UnixNano() > item.Expiration {
			c.mu.RUnlock()
			return nil, false
		}
	}
	item.Count++

	c.mu.RUnlock()
	return item.Object, true
}

//GetWithExpiration 获取缓存和到期时间
func (c *cache) GetWithExpiration(k string) (interface{}, time.Time, bool) {
	c.mu.RLock()
	item, found := c.items[k]
	if !found {
		c.mu.RUnlock()
		return nil, time.Time{}, false
	}

	if item.Expiration > 0 {
		if time.Now().UnixNano() > item.Expiration {
			c.mu.RUnlock()
			return nil, time.Time{}, false
		}

		c.mu.RUnlock()
		return item.Object, time.Unix(0, item.Expiration), true
	}

	c.mu.RUnlock()
	return item.Object, time.Time{}, true
}

//get 获取缓存[内部使用未加锁]
func (c *cache) get(k string) (interface{}, bool) {
	item, found := c.items[k]
	if !found {
		return nil, false
	}
	if item.Expiration > 0 {
		if time.Now().UnixNano() > item.Expiration {
			return nil, false
		}
	}
	return item.Object, true
}

//Increment 递增key
func (c *cache) Increment(k string, n int64) error {
	c.mu.Lock()
	v, found := c.items[k]
	if !found || v.Expired() == Expire {
		c.mu.Unlock()
		return fmt.Errorf("Item %s not found", k)
	}
	switch v.Object.(type) {
	case int:
		v.Object = v.Object.(int) + int(n)
	case int8:
		v.Object = v.Object.(int8) + int8(n)
	case int16:
		v.Object = v.Object.(int16) + int16(n)
	case int32:
		v.Object = v.Object.(int32) + int32(n)
	case int64:
		v.Object = v.Object.(int64) + n
	case uint:
		v.Object = v.Object.(uint) + uint(n)
	case uintptr:
		v.Object = v.Object.(uintptr) + uintptr(n)
	case uint8:
		v.Object = v.Object.(uint8) + uint8(n)
	case uint16:
		v.Object = v.Object.(uint16) + uint16(n)
	case uint32:
		v.Object = v.Object.(uint32) + uint32(n)
	case uint64:
		v.Object = v.Object.(uint64) + uint64(n)
	case float32:
		v.Object = v.Object.(float32) + float32(n)
	case float64:
		v.Object = v.Object.(float64) + float64(n)
	default:
		c.mu.Unlock()
		return fmt.Errorf("The value for %s is not an integer", k)
	}
	c.items[k] = v
	c.mu.Unlock()
	return nil
}

//Decrement 递增
func (c *cache) Decrement(k string, n int64) error {
	// TODO: Implement Increment and Decrement more cleanly.
	// (Cannot do Increment(k, n*-1) for uints.)
	c.mu.Lock()
	v, found := c.items[k]
	if !found || v.Expired() == Expire {
		c.mu.Unlock()
		return fmt.Errorf("Item not found")
	}
	switch v.Object.(type) {
	case int:
		v.Object = v.Object.(int) - int(n)
	case int8:
		v.Object = v.Object.(int8) - int8(n)
	case int16:
		v.Object = v.Object.(int16) - int16(n)
	case int32:
		v.Object = v.Object.(int32) - int32(n)
	case int64:
		v.Object = v.Object.(int64) - n
	case uint:
		v.Object = v.Object.(uint) - uint(n)
	case uintptr:
		v.Object = v.Object.(uintptr) - uintptr(n)
	case uint8:
		v.Object = v.Object.(uint8) - uint8(n)
	case uint16:
		v.Object = v.Object.(uint16) - uint16(n)
	case uint32:
		v.Object = v.Object.(uint32) - uint32(n)
	case uint64:
		v.Object = v.Object.(uint64) - uint64(n)
	case float32:
		v.Object = v.Object.(float32) - float32(n)
	case float64:
		v.Object = v.Object.(float64) - float64(n)
	default:
		c.mu.Unlock()
		return fmt.Errorf("The value for %s is not an integer", k)
	}
	c.items[k] = v
	c.mu.Unlock()
	return nil
}

//Delete 删除缓存
func (c *cache) Delete(k string) {
	c.mu.Lock()
	v, evicted := c.delete(k)
	c.mu.Unlock()
	if evicted {
		c.onEvicted(CleanItem{
			Key:     k,
			Value:   v.Object,
			Count:   v.Count,
			Invalid: Normal,
		})
	}
}

//delete 删除缓存[内部使用未加锁]
func (c *cache) delete(k string) (*Item,bool) {
	if c.onEvicted != nil {
		if v, found := c.items[k]; found {
			delete(c.items, k)
			return v, true
		}
	}
	delete(c.items, k)
	return nil, false
}

//CleanItem 清理项
type CleanItem struct {
	Key     string      // key
	Value   interface{} // 数据
	Count   int64       // 读取次数
	Invalid DataInvalid // 是否失效
}

//DeleteExpired 清理过期
func (c *cache) DeleteExpired() {
	var evictedItems []CleanItem
	now := time.Now().UnixNano()
	nanoseconds := c.willExpire.Nanoseconds()
	c.mu.Lock()
	for k, v := range c.items {
		unixNano := now - v.Expiration
		if v.Expiration > 0 && unixNano > 0 { //到期
			_, evicted := c.delete(k)
			if evicted {
				evictedItems = append(evictedItems, CleanItem{
					Key:     k,
					Value:   v.Object,
					Invalid: Expire,
					Count:   v.Count,
				})
			}
		} else if nanoseconds > 0 && unixNano > - nanoseconds && !v.firstNotify { //即将到期
			evictedItems = append(evictedItems, CleanItem{
				Key:     k,
				Value:   v.Object,
				Invalid: WillExpire,
				Count:   v.Count,
			})
			v.firstNotify = true
		}
	}
	c.mu.Unlock()
	if len(evictedItems) != 0 {
		c.onEvicted(evictedItems...)
	}
}

//OnEvicted 过期或即将过期的通知
func (c *cache) OnEvicted(f func(items ...CleanItem)) {
	c.mu.Lock()
	c.onEvicted = f
	c.mu.Unlock()
}

//Save Write the cache's items (using Gob) to an io.Writer.
// NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the
// documentation for NewFrom().)
func (c *cache) Save(w io.Writer) (err error) {
	enc := gob.NewEncoder(w)
	defer func() {
		if x := recover(); x != nil {
			err = fmt.Errorf("Error registering item types with Gob library.")
		}
	}()
	c.mu.RLock()
	defer c.mu.RUnlock()
	for _, v := range c.items {
		gob.Register(v.Object)
	}
	err = enc.Encode(&c.items)
	return
}

//SaveFile 把缓存保存到文件
func (c *cache) SaveFile(fname string) error {
	fp, err := os.Create(fname)
	if err != nil {
		return err
	}
	err = c.Save(fp)
	if err != nil {
		fp.Close()
		return err
	}
	return fp.Close()
}

//Load 加载缓存
func (c *cache) Load(r io.Reader) error {
	dec := gob.NewDecoder(r)
	items := map[string]*Item{}
	err := dec.Decode(&items)
	if err == nil {
		c.mu.Lock()
		defer c.mu.Unlock()
		for k, v := range items {
			ov, found := c.items[k]
			if !found || ov.Expired() == Normal {
				c.items[k] = v
			}
		}
	}
	return err
}

//LoadFile 加载文件缓存
func (c *cache) LoadFile(fname string) error {
	fp, err := os.Open(fname)
	if err != nil {
		return err
	}
	err = c.Load(fp)
	if err != nil {
		fp.Close()
		return err
	}
	return fp.Close()
}

//Items Copies all unexpired items in the cache into a new map and returns it.
func (c *cache) Items() map[string]*Item {
	c.mu.RLock()
	defer c.mu.RUnlock()
	m := make(map[string]*Item, len(c.items))
	now := time.Now().UnixNano()
	for k, v := range c.items {
		if v.Expiration > 0 {
			if now > v.Expiration {
				continue
			}
		}
		m[k] = v
	}
	return m
}

//ItemCount 获取缓存个数
func (c *cache) ItemCount() int {
	c.mu.RLock()
	n := len(c.items)
	c.mu.RUnlock()
	return n
}

//Flush 清理缓存
func (c *cache) Flush() {
	c.mu.Lock()
	c.items = map[string]*Item{}
	c.mu.Unlock()
}

type janitor struct {
	Interval time.Duration
	stop     chan bool
}

func (j *janitor) Run(c *cache) {
	ticker := time.NewTicker(j.Interval)
	for {
		select {
		case <-ticker.C:
			c.DeleteExpired()
		case <-j.stop:
			ticker.Stop()
			return
		}
	}
}

func stopJanitor(c *Cache) {
	c.janitor.stop <- true
}

func runJanitor(c *cache, ci time.Duration) {
	j := &janitor{
		Interval: ci,
		stop:     make(chan bool),
	}
	c.janitor = j
	go j.Run(c)
}

func newCache(de, will time.Duration, m map[string]*Item) *cache {
	if de == 0 {
		de = -1
	}
	c := &cache{
		defaultExpiration: de,
		willExpire:        will,
		items:             m,
	}
	return c
}

func newCacheWithJanitor(de , ci, will time.Duration, m map[string]*Item) *Cache {
	c := newCache(de,will, m)
	C := &Cache{c}
	if ci > 0 {
		runJanitor(c, ci)
		runtime.SetFinalizer(C, stopJanitor)
	}
	return C
}

// NewCache 创建缓存
// defaultExpiration 默认过期时间[小于0不过期]
// cleanupInterval   定时清理过期项时间
// willExpire        提前通知将到期key时间秒[设置此项将会调用两次到期通知，在快要到期时一次，到期时一次]
func NewCache(defaultExpiration, cleanupInterval, willExpire time.Duration) *Cache {
	items := make(map[string]*Item)
	return newCacheWithJanitor(defaultExpiration, cleanupInterval,willExpire, items)
}

